package com.ruoyi.businessOrder.service.impl;

import cn.elegent.pay.ElegentPay;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.businessOrder.domain.BusinessOrder;
import com.ruoyi.businessOrder.domain.dto.BusinessOrderDto;
import com.ruoyi.businessOrder.domain.dto.RefundApplyDto;
import com.ruoyi.businessOrder.domain.dto.RefundAuditDto;
import com.ruoyi.businessSku.domain.BusinessSku;
import com.ruoyi.businessSku.mapper.BusinessSkuMapper;
import com.ruoyi.businessSku.service.IBusinessSkuService;
import com.ruoyi.common.config.WxPaymentConfig;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.wxpay.WxApiType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.employee.domain.Employee;
import com.ruoyi.employee.service.IEmployeeService;
import com.ruoyi.organization.domain.Organization;
import com.ruoyi.organization.service.IOrganizationService;
import com.ruoyi.payLog.domain.PayLogs;
import com.ruoyi.payLog.mapper.PayLogsMapper;
import com.ruoyi.payLog.service.IPayLogsService;
import com.ruoyi.refundInfo.domain.RefundInfo;
import com.ruoyi.refundInfo.mapper.RefundInfoMapper;
import com.ruoyi.refundInfo.service.IRefundInfoService;

import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.businessOrder.mapper.BusinessOrderMapper;
import com.ruoyi.businessOrder.service.IBusinessOrderService;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.security.Signature;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 交易订单信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-06-11
 */
@Service
public class BusinessOrderServiceImpl implements IBusinessOrderService {

    private static final Logger log = LoggerFactory.getLogger(BusinessOrderServiceImpl.class);

    @Autowired
    private BusinessOrderMapper businessOrderMapper;

    @Autowired
    private BusinessSkuMapper businessSkuMapper;

    @Autowired
    private RefundInfoMapper refundInfoMapper;

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IOrganizationService organizationService;

    @Autowired
    private IBusinessOrderService businessOrderService;

    @Autowired
    private IBusinessSkuService businessSkuService;

    @Autowired
    private IPayLogsService payLogsService;

    @Autowired
    private PayLogsMapper payLogsMapper;

    @Autowired
    private IRefundInfoService refundInfoService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ElegentPay elegentPay;

    @Autowired
    private WxPaymentConfig wxPaymentConfig;

    @Autowired
    private CloseableHttpClient wxPaymentClient;

    @Autowired
    private SysUserServiceImpl sysUserServiceImpl;

    // 订单基础校验
    private void validateOrderForPayment(BusinessOrder order) {
        // 订单基础校验
        if (order == null) {
            throw new ServiceException("订单不存在");
        }

        // 订单超时校验
        if (order.getExpireTime().before(new Date())) {
            throw new ServiceException("订单已过期");
        }

        // 订单状态校验
        if (!"0".equals(order.getPayStatus())) {
            throw new ServiceException("订单状态异常");
        }

    }

    /**
     * 构建返回结果
     *
     * @param order 订单信息
     * @param result 微信返回结果
     * @return 构建结果
     */
    private HashMap<String, Object> buildResponse(BusinessOrder order, Map<String, String> result) {
        HashMap<String, Object> map = new HashMap<>();
        // 预交易订单编号
        map.put("prepayId", result.get("prepay_id"));
        // 订单编号
        map.put("orderCode", order.getOrderCode());
        // 过期时间
        map.put("expireTime", order.getExpireTime().getTime());

        return map;
    }

    /**
     * 小程序获取预支付id
     *
     * @param orderId 交易商品信息主键
     * @return 交易订单信息
     */
    @Override
    public HashMap<String, Object> miniAppGetPrePayId(Long orderId) throws Exception {

        log.info("发起支付请求, 获取预支付id");
        // 支付的前提，当前订单的业务订单信息和支付日志信息已经存在数据库中
        // 订单基础校验
        BusinessOrder order = businessOrderService.selectBusinessOrderByOrderId(orderId);
        validateOrderForPayment(order);

//        String existingCodeUrl = order.getQrCodeParams();
//        String existingPrepayId = order.getTransactionId();
//
//        if (order != null && !StringUtils.isEmpty(existingCodeUrl)) {
//            log.info("订单已存在，返回订单信息");
//            // 【7】返回结果
//            HashMap<String, Object> map = new HashMap<>();
//            map.put("prepayId", existingPrepayId);
//            map.put("orderCode", existingCodeUrl);
//            // 二维码地址
//            map.put("codeUrl", existingCodeUrl);
//            // 订单超时时间
//            map.put("expireTime", order.getExpireTime().getTime());
//
//            return map;
//        }
//
//        // 新增：验证订单有效性
//        if (order.getExpireTime() != null && order.getExpireTime().before(new Date())) {
//            log.warn("尝试支付已过期订单，订单ID: {}", orderId);
//            // 新增：调用关闭订单接口
//            try {
//                miniAppCloseOrder(orderId); // 同步关闭订单
//            } catch (Exception e) {
//                log.error("关闭过期订单失败，订单ID: {}", orderId, e);
//                // 可选：记录关闭失败日志，后续通过定时任务补偿
//            }
//            throw new ServiceException("订单已过期，请重新下单");
//        }

        // 支付幂等性校验 校验支付日志是否存在且状态为待支付
        // 订单支付日志基础校验
        PayLogs existingPayLogs = payLogsService.selectPayLogsByOrderId(orderId);
        // 存在且状态不为待支付
        if (existingPayLogs != null) {
            // handleExistingPaymentLog(existingPayLogs, order);

            // 如果 prepayId 或 codeUrl 为空，重新调用微信下单
            // 空字符串会被误判为"非空"
            if (StringUtils.isNotEmpty(existingPayLogs.getPrepayId()))
            {
                // 重新调用微信统一下单接口
                HashMap<String, Object> map = new HashMap<>();
                map.put("prepayId", existingPayLogs.getPrepayId());
                map.put("orderCode", order.getOrderCode());
                map.put("expireTime", order.getExpireTime().getTime());
                return map;
            }
        }

        log.info("调用JSAPI/小程序统一下单API");
        // 【1】创建HTTP请求, 请求https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi JSAPI/小程序下单接口
        HttpPost httpPost = new HttpPost(wxPaymentConfig.getDomain().concat(WxApiType.JSAPI_PAY.getType()));

        // 【2】封装下单请求Body参数
        log.info("封装下单请求Body参数");
        // 创建JSON对象
        ObjectMapper objectMapper = new ObjectMapper();
        // 创建表单对象
        Map params = new HashMap<>();

        // 微信小程序下单请求, Body参数:
        // appid
        params.put("appid", wxPaymentConfig.getAppid());
        // mchid
        params.put("mchid", wxPaymentConfig.getMchId());
        // 商品描述
        params.put("description", order.getBusinessName());
        // 订单号, 每次调用获取预支付订单编号时都生成一个新的微信交易编号
        params.put("out_trade_no", order.getOrderCode());
        // 支付结束时间（选填）
//        params.put("time_expire", generateTimeExpire());
        if (order.getExpireTime() != null) {
            // 使用订单原始过期时间
            params.put("time_expire", order.getExpireTime().toInstant()
                    .atZone(ZoneId.of("Asia/Shanghai"))
                    .format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
        } else {
            // 紧急情况回退机制
            params.put("time_expire", generateTimeExpire());
            log.warn("订单{}未设置过期时间，使用默认时间", orderId);
        }
        // 商户数据包（选填）

        // 支付回调地址
        params.put("notify_url", wxPaymentConfig.getNotifyDomain() + "/wxpay/pay");

        // 订单优惠标记（选填）
        // 电子发票入口开放标识（选填）

        // 金额设置 订单总金额，单位为分，整型。示例：1元应填写 100（微信支付要求）
        BigDecimal amountYuan = order.getAmount();
        log.info("订单金额: {} 元", amountYuan); // 0.01元
//        long totalFee = amountYuan.multiply(new BigDecimal(100)).longValue();

        // 元转分（精确转换）
        long totalFee = amountYuan.multiply(BigDecimal.valueOf(100))
                .setScale(0, BigDecimal.ROUND_HALF_UP)
                .longValue(); // 0.01 * 100 = 1分
        log.info("转换后金额(分): {}", totalFee); // 1分


        Map<String, Object> amount = new HashMap<>();
        amount.put("total", totalFee);
        amount.put("currency", "CNY");
        // 订单金额
        params.put("amount", amount);

        // 支付者信息
        // 获取当前用户ID
        Long userId = SecurityUtils.getUserId();
        // 根据用户ID, 获取当前用户信息
        SysUser user = userService.selectUserById(userId);
        // 获取当前用户微信openid
        String openid = user.getOpenId();

        log.info("用户openid: {}", openid);
        if (StringUtils.isEmpty(openid)) {
            throw new ServiceException("用户未绑定 openid");
        }

        Map<String, Object> payer = new HashMap<>();
        payer.put("openid", openid);
        // 订单支付者信息
        params.put("payer", payer);
        // 优惠功能（选填）

        // 场景信息
//        Map<String, Object> sceneInfo = new HashMap<>();
//        sceneInfo.put("payer_client_ip", user.getLoginIp());
//        params.put("scene_info", sceneInfo);
        // 结算信息（选填）

        // 【3】订单参数转为json
        String jsonBody = objectMapper.writeValueAsString(params);

        // 【4】创建请求体
        StringEntity entity = new StringEntity(jsonBody, "utf-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept", "application/json");

        // 执行请求
        CloseableHttpResponse response = wxPaymentClient.execute(httpPost);
        // 响应体
        String result = EntityUtils.toString(response.getEntity(), "UTF-8");
        // 响应状态码
        int statusCode = response.getStatusLine().getStatusCode();

        // 【5】执行请求
        try {
            if (statusCode == 200) {
                log.info("请求成功, 返回结果 = " + result);
            } else if (statusCode == 204) {
                log.info("请求成功，无返回结果");
            } else {
                System.out.println("下单失败，响应码 = " + statusCode + "返回结果 = " + result);
                throw new IOException("请求失败");
            }

            // 【6】解析响应结果
            Map<String, String> resultMap = objectMapper.readValue(result, Map.class);

            String prepayId = resultMap.get("prepay_id");
            // 更新支付日志信息
            existingPayLogs.setPrepayId(prepayId);

            payLogsService.updatePayLogs(existingPayLogs);

            // 获取预支付ID后，启动定时任务检查支付状态
            scheduleOrderTimeoutTask(orderId);

            // 6. 返回结果封装
            return buildResponse(order, resultMap);

        } finally {
            response.close();
        }

    }

    /**
     * 启动定时任务检查支付状态
     *
     * @param orderId 订单ID
     */
    private void scheduleOrderTimeoutTask(Long orderId) {
        try {
            BusinessOrder order = businessOrderService.selectBusinessOrderByOrderId(orderId);
            if (order == null) return;

            Date now = DateUtils.getNowDate();
            // 订单超时延时
            long timeoutDelay = order.getExpireTime().getTime() - now.getTime();

            // 修复点1：增加延迟校验
            if (timeoutDelay <= 0) {
                log.warn("订单{}已过期，立即执行超时检查", orderId);
                // 立即执行支付状态检查
                checkPaymentStatus(orderId);
                return;
            }

            // 修复点2：使用ScheduledExecutorService替代Timer
            ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
            executor.schedule(() -> {
                try {
                    checkPaymentStatus(orderId);
                } finally {
                    executor.shutdown();
                }
            }, timeoutDelay, TimeUnit.MILLISECONDS);

        } catch (Exception e) {
            log.error("定时任务调度失败，订单ID: {}", orderId, e);
        }
    }

    /**
     * 支付状态检查
     *
     * @param orderId 订单ID
     */
    private void checkPaymentStatus(Long orderId) {
        try {
            BusinessOrder order = businessOrderService.selectBusinessOrderByOrderId(orderId);
            if (order != null && "1".equals(order.getPayStatus())) {
                log.info("订单已支付，无需关闭，orderId: {}", orderId);
                return;
            }

            // 订单未支付，调用关闭订单接口
            log.info("订单支付超时，开始关闭订单，orderId: {}", orderId);
            HashMap<String, Object> closeResult = miniAppCloseOrder(orderId);
            boolean success = (boolean) closeResult.get("success");
            boolean closed = (boolean) closeResult.get("closed");
            boolean userPaying = (boolean) closeResult.get("userPaying");
            if (success) {
                log.info("订单关闭成功，orderId: {}", orderId);

            } else if (closed) {
                log.error("订单关闭失败，orderId: {}", orderId);

            } else if (userPaying) {
                log.info("用户正在支付，等待支付结果，orderId: {}", orderId);

            } else {
                log.error("订单关闭失败，订单已支付，orderId: {}", orderId);

            }
        } catch (Exception e) {
            log.error("支付状态检查失败，订单ID: {}", orderId, e);
        }
    }


    // 新增重试调度方法
    private void scheduleOrderTimeoutTask(Long orderId, int retryCount) {
        long delay = Math.min(retryCount * 5 * 60 * 1000, 30 * 60 * 1000); // 最大30分钟

        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        executor.schedule(() -> {
            try {
                checkPaymentStatus(orderId);
            } finally {
                executor.shutdown();
            }
        }, delay, TimeUnit.MILLISECONDS);
    }


    /**
     * 获取微信支付参数
     * @param orderId, oderNo, totalFee, openId
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, String> getWxpayParams(Long orderId, String orderNo, Integer totalFee, String openId) throws Exception {

        // 根据orderId,获取业务订单信息
        BusinessOrder order = businessOrderService.selectBusinessOrderByOrderId(orderId);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        // 数据库中订单表的金额是元为单位
        BigDecimal amountYuan = order.getAmount(); // 0.01元
        // 数据库中的金额转换成分为单位 * 100
        int amountFen = amountYuan.multiply(BigDecimal.valueOf(100)).intValue(); // 1分
        log.info("前端金额: {}分, 数据库金额: {}分", totalFee, amountFen);

        // 前端传回的金额是以分为单位的
        if (totalFee != amountFen) {
            throw new ServiceException("支付金额与订单金额不一致");
        }

        log.info("获取微信支付参数");
        // 调用JSAPI/小程序下单接口，返回的prepay_id参数值
        HashMap<String, Object> response = miniAppGetPrePayId(orderId);
        // 获取 prepay_id
        String prepayId = (String) response.get("prepayId");

        // 封装参数
        Map<String, String> payParams = new HashMap<>();
        // appId（必填）
        // payParams.put("appid", wxPaymentConfig.getAppid());
        // 当前时间戳（秒，必填）。注意：部分系统取到的值为毫秒级，商户需要转换成秒(10位数字)
        payParams.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));
        // 随机字符串（必填）
        payParams.put("nonceStr", generateNonceStr(32));
        // 格式固定为"prepay_id=xxx"（必填）
        payParams.put("package", "prepay_id=" + prepayId);
        // 签名类型（与统一下单一致，必填）
        payParams.put("signType", "RSA");

//        // 商品描述（必填）
//        payParams.put("body", "商品描述（如：XX订单支付）");
//        // 客户端IP（可从请求中获取，如request.getRemoteAddr()）
//        payParams.put("spbill_create_ip", IpUtils.getIpAddr());

//        // 支付金额（分，必填）
//        payParams.put("total_fee", String.valueOf(totalFee));
//        // 订单号（唯一，必填）
//        payParams.put("order_no", orderNo);
//        // 用户OpenID（JSAPI必填）
//        payParams.put("openid", openId);

        // 7. 生成RSA签名（严格按照微信规范）
        payParams.put("paySign", generatePaySign(
                wxPaymentConfig.getAppid(),
                payParams.get("timeStamp"),
                payParams.get("nonceStr"),
                payParams.get("package") // 完整package字符串
        ));

        return payParams;
    }



    /**
     * 关闭订单
     * @param orderId
     * @return
     */
    @Override
    public HashMap<String, Object> miniAppCloseOrder(Long orderId) throws Exception {

        // 根据订单ID, 获取当前订单信息
        BusinessOrder order = businessOrderService.selectBusinessOrderByOrderId(orderId);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }

        if ("2".equals(order.getOrderStatus())) {
            log.info("订单已关闭，无需重复操作，orderId: {}", orderId);
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("success", true);
            return resultMap;
        }

        // 获取已支付的业务订单信息
        PayLogs payLogs = payLogsService.selectPayLogsByOrderId(orderId);

        log.info("获取已支付的业务订单信息，调用关闭订单的接口");
        // 【1】构造带路径参数的URL
        String closeOrderUrl = wxPaymentConfig.getDomain() + WxApiType.CLOSE_ORDER.getType()
                .replace("{out_trade_no}", order.getOrderCode());

        log.info("调用关闭订单API", closeOrderUrl);
        // 创建HTTP请求, 请求https://api.mch.weixin.qq.com//v3/pay/transactions/out-trade-no/{out_trade_no}/close 关闭订单接口
        HttpPost httpPost = new HttpPost(closeOrderUrl);

        // 【2】封装关闭订单请求的Body参数
        log.info("封装关闭订单请求的Body参数");
        // 创建JSON对象
        ObjectMapper objectMapper = new ObjectMapper();
        // 创建表单对象
        Map<Object, Object> params = new HashMap<>();

        // 微信小程序关闭订单请求, Body参数:
        // 商户号
        params.put("mchid", wxPaymentConfig.getMchId());

        // 【3】订单参数转为json
        String jsonBody = objectMapper.writeValueAsString(params);

        // 【4】创建请求体
        StringEntity entity = new StringEntity(jsonBody, "utf-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept", "application/json");

        try (CloseableHttpResponse response = wxPaymentClient.execute(httpPost)) {
            int statusCode = response.getStatusLine().getStatusCode();
            String result = "";

            // 仅当响应体存在时解析内容
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                result = EntityUtils.toString(responseEntity, "UTF-8");
            } else {
                log.warn("关闭订单API返回空响应体，订单ID: {}, 状态码: {}", orderId, statusCode);
            }

            // 【5】处理响应结果
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("success", false);

            if (statusCode == 204) {
                log.info("订单关闭成功，订单ID: {}", orderId);
                resultMap.put("success", true);

                // 更新订单状态为关闭
                order.setOrderStatus("2"); // 订单关闭
                int rows = businessOrderService.updateBusinessOrder(order);
                if (rows <= 0) {
                    log.error("订单关闭状态更新失败，订单ID: {}", orderId);
                }

                // 更新订单支付日志信息
                payLogs.setPaymentStatus("2"); // 支付失败
                int logRows = payLogsService.updatePayLogs(payLogs);
                if (logRows <= 0) {
                    log.error("订单支付日志状态更新失败，订单ID: {}", orderId);
                }
            } else {
                log.error("关闭订单失败，订单ID: {}, 状态码: {}, 响应: {}", orderId, statusCode, result);
                resultMap.put("errorCode", statusCode);
                resultMap.put("errorMsg", result);
            }

            return resultMap;
        }
    }

    /**
     * 用户申请退款
     * 事务说明：
     * 1. 创建新的退款申请记录
     * 2. 更新订单状态
     * 3. 以上操作必须原子执行，任一失败则回滚
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void applyRefund(RefundApplyDto refundApplyDto) {
        // 1. 验证订单是否存在
        BusinessOrder order = selectBusinessOrderByOrderId(refundApplyDto.getOrderId());
        if (order == null) {
            throw new ServiceException("订单不存在");
        }

        // 2. 验证订单状态（已支付才能申请退款）
        if (!"1".equals(order.getOrderStatus())) {
            throw new ServiceException("只有已支付订单才能申请退款");
        }

        // 3. 检查是否有"处理中"的退款申请（关键修改）
        List<RefundInfo> activeRefunds = refundInfoService.selectActiveRefundsByOrderId(refundApplyDto.getOrderId());
        if (!activeRefunds.isEmpty()) {
            throw new ServiceException("该订单已有处理中的退款申请");
        }

        // 4. 验证订单的支付记录是否存在
        PayLogs payLogs = payLogsService.selectPayLogsByOrderId(refundApplyDto.getOrderId());
        if (payLogs == null) {
            throw new ServiceException("支付记录不存在");
        }

        // 5. 创建新的退款申请记录
        RefundInfo refundInfo = new RefundInfo();
        refundInfo.setOrderId(refundApplyDto.getOrderId());
        refundInfo.setPaymentId(payLogs.getPaymentId());
        log.info("创建新的退款申请");

        // 6. 设置退款金额（默认为订单金额）
        BigDecimal refundAmount = refundApplyDto.getAmount() != null ?
                refundApplyDto.getAmount() : order.getAmount();
        if (refundAmount.compareTo(payLogs.getAmount()) > 0) {
            throw new ServiceException("退款金额不能超过支付金额");
        }
        refundInfo.setRefundAmt(refundAmount);

        // 7. 设置退款原因
        refundInfo.setReason(refundApplyDto.getReason());
        // 8. 设置审核状态为"待审核"
        refundInfo.setRefundAuditStatus("0");
        // 9. 设置退款状态为"申请中"
        refundInfo.setRefundStatus("1");
        // 10. 生成退款单号
        refundInfo.setRefundCode(IdUtils.generateRefundCode());

        // 11. 保存退款申请
        refundInfoService.insertRefundInfo(refundInfo);
        log.info("成功创建退款申请，退款ID: {}", refundInfo.getRefundId());

        // 12. 更新订单状态为"退款申请中"
        // 如果订单当前状态不是"已支付"，则可能已经有退款申请在处理
        if (!"1".equals(order.getOrderStatus())) {
            log.warn("订单状态异常，当前状态: {}", order.getOrderStatus());
        }

        // 如果已有退款申请，状态可能已经是"3"（退款中）
        if (!"3".equals(order.getOrderStatus())) {
            order.setOrderStatus("3");
            businessOrderMapper.updateBusinessOrder(order);
            log.info("成功更新订单状态为退款申请中，订单ID: {}", order.getOrderId());
        }
    }

    /**
     * 退款审核
     * 参数：审核结果、审核理由
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditRefundApplication(Long refundId, RefundAuditDto auditDto) throws Exception {
        // 1. 获取退款申请
        RefundInfo refundInfo = refundInfoService.selectRefundInfoByRefundId(refundId);
        if (refundInfo == null) {
            throw new ServiceException("退款申请不存在");
        }

        // 获取订单
        BusinessOrder order = businessOrderService.selectBusinessOrderByOrderId(refundInfo.getOrderId());
        if (order == null) {
            throw new ServiceException("订单不存在");
        }

        // 2. 验证退款申请状态（必须是待审核）
        if (!"0".equals(refundInfo.getRefundAuditStatus())) {
            throw new ServiceException("退款申请状态异常，无法审核");
        }

        // 3. 更新退款申请审核信息
        refundInfo.setRefundAuditStatus(auditDto.getAuditStatus());
        refundInfo.setAuditRemark(auditDto.getAuditReason());
        refundInfo.setAuditTime(new Date());
        refundInfo.setAuditBy(SecurityUtils.getUsername());

        // 4. 处理审核结果
        if ("1".equals(auditDto.getAuditStatus())) { // 审核通过
            // 先更新退款状态为"2=退款中"
            refundInfo.setRefundStatus("2");
            refundInfo.setRefundAuditStatus("1");
            refundInfoService.updateRefundInfo(refundInfo);
            try {
                // 执行微信退款（同步操作）
                HashMap<String, Object> refundResult = miniAppRefund(refundInfo.getOrderId(), refundInfo.getReason());
                // 执行微信退款（同步操作）
                // 验证退款结果
                if (refundResult != null && (Boolean) refundResult.get("success")) {
                    String refundTransId = (String) refundResult.get("refundTransId");
                    // 1. 更新退款记录状态
                    refundInfo.setRefundStatus("3"); // 已退款
                    refundInfo.setRefundTransId(refundTransId);
                    refundInfo.setRefundTime(new Date());
                    refundInfoService.updateRefundInfo(refundInfo);
                    log.info("更新退款状态为：已退款，微信退款单号：{}", refundTransId);

                    // 2. 更新订单状态
                    order.setOrderStatus("4"); // 已退款
                    businessOrderService.updateBusinessOrder(order);
                    log.info("更新订单状态为：已退款，订单ID：{}", order.getOrderId());

                    // 3. 更新支付日志
                    PayLogs payLogs = payLogsService.selectPayLogsByOrderId(refundInfo.getOrderId());
                    if (payLogs != null) {
                        payLogs.setRefundAmount(refundInfo.getRefundAmt());
                        payLogs.setRefundStatus("3"); // 已退款
                        payLogs.setRefundTime(new Date());
                        payLogsService.updatePayLogs(payLogs);
                        log.info("更新支付日志中的退款相关数据");
                    }
                    // ===== 更新结束 =====
                } else {
                    throw new ServiceException("微信退款返回异常结果");
                }
                // miniAppRefund(refundInfo.getOrderId(), refundInfo.getReason());
                // 注意：miniAppRefund 内部已更新订单状态为"4"

            } catch (Exception e) {
                // 退款失败，回滚状态
                refundInfo.setRefundStatus("4"); // 退款失败
                refundInfoService.updateRefundInfo(refundInfo);
                throw e;
            }
            // 执行微信退款
            // miniAppRefund(refundInfo.getOrderId(), refundInfo.getReason());
        } else if ("2".equals(auditDto.getAuditStatus())) { // 审核拒绝
            // 更新退款审核状态为"审核驳回"
            refundInfo.setRefundAuditStatus("2");
            refundInfo.setAuditRemark(auditDto.getAuditReason());
            refundInfo.setAuditTime(new Date());
            refundInfo.setAuditBy(SecurityUtils.getUsername());

            refundInfoService.updateRefundInfo(refundInfo);

            // 检查是否还有其他处理中的退款申请
            List<RefundInfo> processingRefunds = refundInfoService.selectActiveRefundsByOrderId(refundInfo.getOrderId());
            if (processingRefunds.isEmpty()) {
                // 没有其他有效退款申请，恢复订单状态
                order.setOrderStatus("1"); // 已支付
                businessOrderService.updateBusinessOrder(order);
                log.info("订单状态已恢复为已支付，订单ID: {}", order.getOrderId());
            } else {
                log.info("订单ID: {} 仍有 {} 个处理中的退款申请，不恢复订单状态",
                        order.getOrderId(), processingRefunds.size());
            }

        }

        // 5. 保存退款审核记录
        refundInfoService.updateRefundInfo(refundInfo);
    }


    /**
     * 微信退款
     *
     * @param orderId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public HashMap<String, Object> miniAppRefund(Long orderId, String reason) throws Exception {

        // 根据订单ID, 获取当前订单信息
        BusinessOrder order = businessOrderService.selectBusinessOrderByOrderId(orderId);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        // 订单在数据库中的金额
        BigDecimal amountYuan = order.getAmount(); // 0.01元
        // 数据库中的金额转换成分
        int amountFen = amountYuan.multiply(BigDecimal.valueOf(100)).intValue(); // 1分
        log.info("转换后的金额: {}分", amountFen); // 1分

        // 获取已支付的业务订单信息
        PayLogs payLogs = payLogsService.selectPayLogsByOrderId(orderId);
        if (payLogs == null) {
            throw new ServiceException("未找到支付记录");
        }
//        if (payLogs == null) {
//            throw new ServiceException("未找到支付记录");
//        } else {
//            // 添加退款金额至支付记录中
//            BigDecimal paymentAmount = payLogs.getAmount();
//            BigDecimal refundAmount = amountYuan;
//            // 校验金额合法性
//            if (paymentAmount == null || refundAmount == null) {
//                throw new ServiceException("支付金额或退款金额为空");
//            }
//
//            if (refundAmount.compareTo(paymentAmount) > 0) {
//                throw new ServiceException("申请退款金额不能大于已支付金额");
//            }
//            payLogs.setRefundAmount(amountYuan); // 0.01 元
//            payLogsService.updatePayLogs(payLogs);
//
//        }

        // 3. 获取当前退款申请（最新创建的待处理退款）
        RefundInfo refundInfo = refundInfoService.getLatestRefundByOrderId(orderId);
        if (refundInfo == null) {
            throw new ServiceException("未找到退款申请");
        }

        // 4. 验证退款申请状态
        if (!"1".equals(refundInfo.getRefundAuditStatus()) || !"2".equals(refundInfo.getRefundStatus())) {
            throw new ServiceException("退款申请状态异常，无法执行退款");
        }

        // 2. 查询现有退款记录
//        RefundInfo existingRefundInfo = refundInfoService.selectByOrderId(orderId);
        String refundNo = IdUtils.generateRefundCode(); // 退款编号
//        RefundInfo refundInfo;

//        // 1. 存在退款记录
//        if (existingRefundInfo != null) {
//            if ("3".equals(existingRefundInfo.getRefundStatus())) {
//                // 已退款 → 禁止操作
//                throw new ServiceException("订单已退款");
//            } else if ("4".equals(existingRefundInfo.getRefundStatus())) {
//                // 退款失败 → 请重试
//                throw new ServiceException("订单退款失败");
//            }
//        }
//        else {
//            // 新建退款记录
//            refundInfo = new RefundInfo();
//            // 设置订单ID
//            refundInfo.setOrderId(orderId);
//            // 设置支付ID，根据订单号拿到支付信息
//            refundInfo.setPaymentId(payLogs.getPaymentId());
//            // 设置退款金额，默认等于支付金额，存入以元为单位的交易金额
//            refundInfo.setRefundAmt(amountYuan);
//            // 退款状态（0：待退款；1：已退款；2：退款失败）
//            refundInfo.setRefundStatus("0");
//            // 退款原因
//            refundInfo.setReason(reason); // 默认为'用户取消订单'
//            // 设置退款编号
//            refundInfo.setRefundCode(refundNo);
//            // 插入退款信息
//            log.info("创建退款单记录");
//            int logRows = refundInfoService.insertRefundInfo(refundInfo);
//            if (logRows <= 0) {
//                log.error("退款日志记录失败，订单ID: {}", orderId);
//                // 可根据业务需求决定是否抛出异常
//                throw new ServiceException("退款日志记录失败");
//            }
//        }

        log.info("开始处理微信退款请求");
        // 退款回调地址
        String notifyUrl = wxPaymentConfig.getNotifyDomain() + "/wxpay/refund";

        // 微信小程序申请退款请求Body参数:
        log.info("封装退款请求的Body参数");
        // 创建表单对象
        Map<Object, Object> params = new HashMap<>();
        // 商户订单号【transaction_id和out_trade_no必须二选一进行传参。】
        params.put("out_trade_no", order.getOrderCode());
        // 商户退款单号
        params.put("out_refund_no", refundNo);
        // 退款原因（选填）
        params.put("reason", reason);
        // 退款结果回调地址(选填)
        params.put("notify_url", notifyUrl);
        // 退款资金来源
        // 退款金额 【退款金额，币种的最小单位，只能为整数，不能超过原订单支付金额】
        // 金额设置 订单总金额，单位为分，整型。示例：1元应填写 100
        // BigDecimal amountYuan = order.getAmount();
        // log.info("订单金额: {} 元", amountYuan);
        long refundFee = amountYuan.multiply(new BigDecimal(100)).longValue();
        log.info("转换后金额(元): {}", refundFee);

        // 退款金额和原订单金额设计为一致
        Map<String, Object> amountMap = new HashMap<>();
        amountMap.put("refund", refundFee); // 退款金额，单位为分
        amountMap.put("total", refundFee);  // 订单金额，单位为分
        amountMap.put("currency", "CNY");   // 币种，CNY：人民币
        params.put("amount", amountMap);
        // 退款商品(选填）

        // 创建JSON对象
        ObjectMapper objectMapper = new ObjectMapper();
        // 订单参数转为json
        String jsonBody = objectMapper.writeValueAsString(params);

        // 构造退款API的URL
        log.info("调用申请退款订单API");
        String refundOrderUrl = wxPaymentConfig.getDomain() + WxApiType.REFUND.getType();
        // 创建HTTP请求, 请求https://api.mch.weixin.qq.com/v3/refund/domestic/refunds 申请退款接口
        HttpPost httpPost = new HttpPost(refundOrderUrl);

        // 创建请求对象
        StringEntity entity = new StringEntity(jsonBody, "utf-8");
        entity.setContentType("application/json");  // 设置请求内容类型为JSON
        httpPost.setEntity(entity);  // 设置请求体
        httpPost.setHeader("Accept", "application/json"); // 设置响应内容类型为JSON

        // 发送请求并获取响应
        try (CloseableHttpResponse response = wxPaymentClient.execute(httpPost)) {
            int statusCode = response.getStatusLine().getStatusCode();
            // 返回的应答参数
            String result = EntityUtils.toString(response.getEntity(), "UTF-8");

            // 在微信退款API调用成功后添加以下代码
            if (statusCode == 200) {
                // 1. 解析微信返回的退款结果
                // Map<String, Object> resultMap = objectMapper.readValue(result, new TypeReference<Map<String, Object>>() {});
                Map<String, String> resultMap = objectMapper.readValue(result, Map.class);
                String refundTransId = (String) resultMap.get("refund_id");

                // 2. 更新退款记录状态
//                refundInfo.setRefundStatus("3"); // 已退款
//                refundInfo.setRefundTransId(refundTransId);
//                refundInfo.setRefundTime(new Date());
//                refundInfoService.updateRefundInfo(refundInfo);
//                log.info("更新退款状态为：已退款，微信退款单号：{}", refundTransId);
//
//                // 3. 更新订单状态
//                order.setOrderStatus("3"); // 已退款
//                businessOrderService.updateBusinessOrder(order);
//                log.info("更新订单状态为：已退款，订单ID：{}", orderId);
//
//                payLogs.setRefundAmount(refundInfo.getRefundAmt());
//                payLogs.setRefundStatus("3"); // 已退款
//                payLogs.setRefundTime(new Date());
//                payLogsService.updatePayLogs(payLogs);
//                log.info("更新支付日志中的退款相关数据");

                // 返回成功结果
                HashMap<String, Object> map = new HashMap<>();
                map.put("success", true);
                map.put("refundId", refundTransId);
                return map;
            } else {
                // 退款失败处理
                refundInfo.setRefundStatus("4"); // 退款失败
                refundInfoService.updateRefundInfo(refundInfo);
                log.error("微信退款失败，订单ID：{}，状态码：{}", orderId, statusCode);
                throw new ServiceException("微信退款失败，状态码：" + statusCode);
            }

//            if (statusCode != 200 && statusCode != 204) {
//                log.error("微信退款失败，状态码: {}, 返回: {}", statusCode, result);
//                // 更新退款日志信息
//                // RefundInfo lastRefundInfo = refundInfoService.selectByOrderId(orderId);
//
//                // refundInfo.setRefundStatus("2"); // 退款失败
//                // refundInfoService.updateRefundInfo(refundInfo);
//
//                // 处理退款失败
//                refundInfo.setRefundStatus("4"); // 4=退款失败
//                refundInfoService.updateRefundInfo(refundInfo);
//
//                throw new ServiceException("微信退款失败: " + result);
//            }

            // 解析响应结果
//            Map<String, String> resultMap = objectMapper.readValue(result, Map.class);
//
//            // 微信支付退款单号
//            String refundTransId = resultMap.get("refund_id");
//            log.info("微信支付退款单号: {}", refundTransId);
//            // 微信支付订单号
//            String transactionId = resultMap.get("transaction_id");
//            // 退款渠道
//            String channel = resultMap.get("channel");
//            // 退款入账账户
//            String userReceivedAccount = resultMap.get("user_received_account");
//            // 退款成功时间
//            String successTime = resultMap.get("success_time");
//            // 退款创建时间
//            String createTime = resultMap.get("create_time");
//            // 退款状态
//            String status = resultMap.get("status");
//            // 资金账户
//            String fundsAccount = resultMap.get("funds_account");
//            // 退款金额
//
//
//            // 返回结果
//            HashMap<String, Object> map = new HashMap<>();
//            // 微信支付退款单号
//            map.put("refund_Id", refundTransId);
//            // 商户退款单号
//            if (refundInfo != null) {
//                map.put("out_refund_no", refundInfo.getRefundCode());
//            }
//            // 微信订单号
//            map.put("transaction_Id", transactionId);
//            // 订单号
//            map.put("out_trade_no", order.getOrderCode());
//            // 退款渠道
//            /*  ORIGINAL: 原路退款
//                BALANCE: 退回到余额
//                OTHER_BALANCE: 原账户异常退到其他余额账户
//                OTHER_BANKCARD: 原银行卡异常退到其他银行卡(发起异常退款成功后返回)
//             */
//            map.put("channel", channel);
//            // 退款入账账户 如："招商银行信用卡0403"
//            map.put("user_received_account", userReceivedAccount);
//            // 退款成功时间
//            map.put("success_time", successTime);
//            // map.put("success_time", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date()));
//            // 退款创建时间
//            map.put("create_time", createTime);
//            // 退款状态
//            map.put("status", status);
//            // 资金账户
//            map.put("funds_account", fundsAccount);
            // 退款金额


            // 更新退款日志信息
            // 6. 更新退款记录
//            refundInfo.setRefundStatus("3"); // 已退款
//            refundInfo.setRefundTransId(refundTransId);
//            refundInfo.setRefundTime(new Date());
//            refundInfoService.updateRefundInfo(refundInfo);
//            log.info("更新退款状态为：已退款");

            // 7. 更新支付日志
//            payLogs.setRefundAmount(refundInfo.getRefundAmt());
//            payLogs.setRefundStatus("3"); // 已退款
//            payLogs.setRefundTime(new Date());
//            payLogsService.updatePayLogs(payLogs);
//            log.info("更新支付日志中的退款相关数据");

            // 8. 更新订单状态为：已退款
//            if ("3".equals(refundInfo.getRefundStatus())) { // 已退款
//               order.setOrderStatus("4"); // 已退款
//               businessOrderService.updateBusinessOrder(order);
//               log.info("订单状态已更新为已退款，订单ID: {}", order.getOrderId());
//            }
            // order.setOrderStatus("4"); // 已退款
            // businessOrderService.updateBusinessOrder(order);

//            RefundInfo lastRefundInfo = refundInfoService.selectByOrderId(orderId);
//            if (lastRefundInfo != null) {
//                // 退款状态：已退款
//                lastRefundInfo.setRefundStatus("3");
//                // 退款原因
//                lastRefundInfo.setReason(reason);
//                // 微信支付退款单号
//                lastRefundInfo.setRefundTransId(refundTransId);
//                // 退款时间
//                lastRefundInfo.setRefundTime(new Date());
//                refundInfoService.updateRefundInfo(lastRefundInfo);
//                log.info("更新业务订单退款状态为：已退款");
//
//                // 更新支付日志中的退款时间
//                payLogs.setRefundAmount(lastRefundInfo.getRefundAmt());
//                payLogs.setRefundStatus("1"); // 已退款
//                payLogs.setRefundTime(new Date());
//                payLogsService.updatePayLogs(payLogs);
//                log.info("更新业务订单支付日志中的退款相关数据");
//
//                // 更新业务订单状态为：已退款
//                order.setOrderStatus("4");
//                // 更新业务订单退款ID
//                order.setRefundId(lastRefundInfo.getRefundId());
//                int rows = businessOrderService.updateBusinessOrder(order);
//                if (rows <= 0) {
//                    log.error("订单退款状态更新失败，订单ID: {}", orderId);
//                }
//            }

            // 在 miniAppRefund 方法末尾添加

//            if ("3".equals(refundInfo.getRefundStatus())) { // 已退款
//                order.setOrderStatus("4"); // 已退款
//                int rows = businessOrderService.updateBusinessOrder(order);
//                if (rows > 0) {
//                    log.info("订单状态已成功更新为已退款，订单ID: {}", order.getOrderId());
//                } else {
//                    log.error("订单状态更新失败，订单ID: {}", order.getOrderId());
//                    throw new ServiceException("订单状态更新失败");
//                }
//            }
//            return map;

        } catch (Exception e) {
            log.error("微信退款接口调用异常，订单ID: {}", orderId, e);
            throw new ServiceException("微信退款处理异常: " + e.getMessage());
        }
    }

    /**
     * 生成支付结束时间，遵循 RFC3339 格式
     * @return 格式示例：2025-06-11T12:30:00+08:00
     */
    private String generateTimeExpire() {
        // 默认设置为当前时间 + 15 分钟（可按业务需求调整）
        ZonedDateTime expireTime = ZonedDateTime.now(ZoneId.of("Asia/Shanghai")).plusMinutes(15);
        return expireTime.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
    }

    // 2. 新增随机字符串生成方法
    private String generateNonceStr(int maxLength) {
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < maxLength; i++) {
            sb.append(chars.charAt(random.nextInt(chars.length())));
        }
        return sb.toString();
    }

    // 修正签名方法（关键代码）
    private String generatePaySignII(String appId, String timeStamp, String nonceStr, String packageValue)
            throws Exception {
        // String signData = "appId=" + appId + "&nonceStr=" + nonceStr + "&package=" + packageValue + "&signType=RSA&timestamp=" + timeStamp;
        // 或按微信文档严格拼接（需确认参数顺序）
        String signData = appId + "\n"
                + timeStamp + "\n"
                + nonceStr + "\n"
                + packageValue + "\n";
        log.info("signData: {}", signData);
        // 私钥签名
        PrivateKey privateKey = wxPaymentConfig.getPrivateKey(wxPaymentConfig.getPrivateKeyPath());
        if (privateKey == null) {
            throw new Exception("商户私钥未配置");
        }
        log.info("私钥（privateKey）: {}", privateKey);
        // 签名算法
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(privateKey);
        signature.update(signData.getBytes(StandardCharsets.UTF_8));

        return Base64.getEncoder().encodeToString(signature.sign());
    }

    // 生成小程序支付签名 (RSA-SHA256)
    private String generatePaySign(String appId, String timeStamp, String nonceStr, String packageValue)
            throws Exception {

        // 1. 严格按照微信格式拼接签名串
        String signData = appId + "\n"
                + timeStamp + "\n"
                + nonceStr + "\n"
                + packageValue + "\n"; // 包含完整"prepay_id=xxx"

        // 2. 获取商户私钥
        PrivateKey privateKey = wxPaymentConfig.getPrivateKey(wxPaymentConfig.getPrivateKeyPath());
        if (privateKey == null) {
            throw new Exception("商户私钥未配置");
        }
        // 3. SHA256withRSA签名
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(privateKey);
        signature.update(signData.getBytes(StandardCharsets.UTF_8));
        // 4. Base64编码
        return Base64.getEncoder().encodeToString(signature.sign());
    }

    /**
     * 获取订单信息By商品id
     *
     * @return
     */
    public BusinessOrder selectBusinessOrderBySkuId(Long skuId)
    {
        return businessOrderMapper.selectBusinessOrderBySkuId(skuId);
    }


    /**
     * 查询交易订单信息
     *
     * @param orderId 交易订单信息主键
     * @return 交易订单信息
     */
    @Override
    public BusinessOrder selectBusinessOrderByOrderId(Long orderId)
    {
        return businessOrderMapper.selectBusinessOrderByOrderId(orderId);
    }

    /**
     * 查询交易订单信息列表
     *
     * @param businessOrder 交易订单信息
     * @return 交易订单信息集合
     */
    @Override
    public List<BusinessOrder> selectBusinessOrderList(BusinessOrder businessOrder)
    {
        return businessOrderMapper.selectBusinessOrderList(businessOrder);
    }

    /**
     * 获取业务订单列表时，将订单状态为'3'（退款中）的优先级设为最高，排在最前面
     * 获取订单列表
     */
    @Override
    public List<BusinessOrder> selectBusinessOrderSummaryList(BusinessOrder businessOrder) {
        return businessOrderMapper.selectBusinessOrderSummaryList(businessOrder);
    }

    /**
     * 根据员工工号查询员工信息
     *
     * @param jobCode 员工工号
     * @return 员工信息
     */
    @Override
    public Employee selectEmployeeByCode(String jobCode) {
        return employeeService.selectEmployeeByCode(jobCode);
    }

    /**
     * 根据员工手机号查询员工信息
     *
     */
    @Override
    public Employee selectEmployeeByPhone(String phone) {
        return employeeService.selectEmployeeByPhone(phone);
    }

    /**
     * 根据机构名称查询机构ID
     *
     * @param orgName 机构名称
     * @return 机构ID
     */
    @Override
    public Organization selectOrgIdByName(String orgName) {
        return organizationService.selectOrgIdByName(orgName);
    }

    /**
     * 根据商品id查询商品信息
     *
     */
    @Override
    public BusinessSku selectBusinessSkuBySkuId(Long skuId) {
        return businessSkuService.selectBusinessSkuBySkuId(skuId);
    }


    /**
     * 新增交易订单信息
     *
     * @param businessOrder 交易订单信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BusinessOrder insertBusinessOrder(BusinessOrder businessOrder)
    {
        // 根据当前登录的用户id, 获取用户信息
        Long userId = SecurityUtils.getUserId();
        if (userId == null) {
            log.error("无法获取当前用户ID");
            throw new ServiceException("无法获取当前用户信息");
        }

        // 查询员工信息 只能根据当前登录用户来查询关联的员工信息了
        // 员工表中存在userId, 根据userId获取员工信息
        Employee employee = employeeService.selectEmployeeByUserId(userId);
        if (employee == null) {
            log.error("员工信息不存在，关联的用户ID：{}", businessOrder.getUserId());
            throw new ServiceException("员工信息不存在");
        }

        // 查询机构信息
        Organization organization = selectOrgIdByName(businessOrder.getOrgName());
        if (organization == null) {
            log.error("机构信息不存在，机构名称：{}", businessOrder.getOrgName());
            throw new ServiceException("机构信息不存在");
        }

        // 查询商品信息
        BusinessSku businessSku = selectBusinessSkuBySkuId(businessOrder.getSkuId());
        if (businessSku == null) {
            log.error("关联商品不存在，商品ID: {}", businessOrder.getSkuId());
            throw new ServiceException("关联商品不存在");
        }
        // 初始化订单信息：【必填信息】
        businessOrder.setEmployeeId(employee.getEmployeeId()); // 设置员工ID
        businessOrder.setOrganizationId(organization.getOrganizationId()); // 设置机构ID
        businessOrder.setUserId(userId); // 设置用户ID
        businessOrder.setSkuId(businessSku.getSkuId()); // 设置商品ID
        // 初始化业务订单信息：【选填信息】
        businessOrder.setOrderCode(IdUtils.generateOrderCode()); // 订单编号
        businessOrder.setSubmitTime(DateUtils.getNowDate()); // 订单提交时间
        businessOrder.setOrderStatus("0"); // 订单状态字段 默认状态：0 待支付
        businessOrder.setPayStatus("0"); // 支付状态字段 默认支付状态：0 待支付

        // 初始化业务订单信息：【需处理的信息】
        // 处理逻辑：如果业务名称为空，则添加默认业务名称
        // 设置业务名称（优先使用商品名称）
        if (StringUtils.isEmpty(businessOrder.getBusinessName())) {
            businessOrder.setBusinessName(businessSku.getBusinessName() != null
                    ? businessSku.getBusinessName() : "默认业务");
        }

        // 创建人和创建时间
        businessOrder.setCreateBy(SecurityUtils.getUsername());
        businessOrder.setCreateTime(DateUtils.getNowDate());
        // 过期时间
        businessOrder.setExpireTime(DateUtils.addMinutes(DateUtils.getNowDate(), 15)); // 15分钟后过期

        // 插入业务订单信息
        try {
            int rows = businessOrderMapper.insertBusinessOrder(businessOrder);
            if (rows <= 0) {
                throw new ServiceException("订单插入失败");
            }
        } catch (Exception e) {
            log.error("订单插入失败，订单信息：{}, 错误详情：{}", businessOrder, e.getMessage());
            throw e;
        }

        // 创建返回给前端的结果
        BusinessOrder createResult = new BusinessOrder();
        createResult.setOrderId(businessOrder.getOrderId());
        createResult.setOrderCode(businessOrder.getOrderCode());


        // 同步创建支付日志
        PayLogs payLogs = new PayLogs();
        // 初始化订单支付记录信息：【必填信息】
        payLogs.setOrderId(businessOrder.getOrderId()); // 订单ID
        payLogs.setAmount(businessOrder.getAmount()); // 金额 元为单位（支付金额从订单数据中获取）
        // 初始化订单支付记录信息：【选填信息】
        payLogs.setPaymentStatus("0"); // 支付状态：0=待支付 1=已支付 2=支付失败

        // 插入支付日志
        try {
            int rows1 = payLogsService.insertPayLogs(payLogs);
            if (rows1 <= 0) {
                throw new ServiceException("订单支付记录信息插入失败");
            }
        } catch (Exception e) {
            log.error("订单支付记录信息插入失败，订单信息：{}, 错误详情：{}", payLogs, e.getMessage());
            throw e;
        }

        return createResult;
    }

    /**
     * 修改交易订单信息
     *
     * @param businessOrder 交易订单信息
     * @return 结果
     */
    @Override
    public int updateBusinessOrder(BusinessOrder businessOrder)
    {
        // 修改人和修改时间
        businessOrder.setUpdateBy(SecurityUtils.getUsername());
        businessOrder.setUpdateTime(DateUtils.getNowDate());
        return businessOrderMapper.updateBusinessOrder(businessOrder);
    }

    /**
     * 更新业务订单状态
     *
     */
    @Override
    public void updateOrderStatusByOrderId(Long orderId, String orderStatus) {
        // 获取业务订单
        BusinessOrder businessOrder = businessOrderMapper.selectBusinessOrderByOrderId(orderId);
        businessOrder.setOrderStatus(orderStatus);
        // 更新业务订单
        businessOrderMapper.updateBusinessOrder(businessOrder);
    }

    /**
     * 保存二维码图片地址
     *
     */
    @Override
    public void saveQrCodeUrl(Long orderId, String qrCodeUrl) {

        businessOrderMapper.saveQrCodeUrl(orderId, qrCodeUrl);
    }



    /**
     * 批量删除交易订单信息
     *
     * @param orderIds 需要删除的交易订单信息主键集合
     * @return 结果
     */
    @Override
    public int deleteBusinessOrderByOrderIds(Long[] orderIds)
    {
        return businessOrderMapper.deleteBusinessOrderByOrderIds(orderIds);
    }

    @Override
    public int deleteBusinessOrderByOrderId(Long orderId) {
        return 0;
    }

    @Override
    public void successPay(String orderSn) {

    }

    @Override
    public void failPay(String orderSn) {

    }

    @Override
    public boolean isSuccessPay(String orderSn) {
        return false;
    }

    /**
     * 创建订单
     * @param payDto
     * @param platform
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BusinessOrder createOrder(BusinessOrderDto payDto, String platform) {
        // 新增：获取当前登录用户的ID
        Long userId = SecurityUtils.getUserId();
        if (userId == null) {
            throw new ServiceException("无法获取当前用户信息");
        }
        // 查询员工信息
        Employee employee = employeeService.selectEmployeeByCode(payDto.getJobCode());
        if (employee == null) {
            log.error("员工信息不存在，工号：{}", payDto.getJobCode());
        }
        // 查询机构信息
        Organization organization = organizationService.selectOrgIdByName(payDto.getOrgName());
        if (organization == null) {
            log.error("机构信息不存在，机构名称：{}", payDto.getOrgName());
        }
        // 将 DTO 转换为实体对象
        BusinessOrder businessOrder = new BusinessOrder();

        // === 关键修改：设置缺失字段 ===
        // 基础信息
        businessOrder.setAmount(payDto.getAmount()); // 设置金额
        businessOrder.setBusinessName(payDto.getBusinessName()); // 业务名称

        // 快照信息
        businessOrder.setName(employee.getName());
        businessOrder.setPhone(employee.getPhone());
        businessOrder.setJobCode(employee.getJobCode());
        businessOrder.setOrgName(organization.getOrgName());

        // 状态信息
        businessOrder.setOrderStatus("1"); // 已提交
        businessOrder.setPayStatus("0"); // 待支付
        businessOrder.setStatus("0"); // 正常
        businessOrder.setDelFlag("0"); // 存在

        // 关联信息
        businessOrder.setEmployeeId(employee.getEmployeeId());
        businessOrder.setOrganizationId(organization.getOrganizationId());
        businessOrder.setUserId(userId);

        // 时间信息
        businessOrder.setSubmitTime(DateUtils.getNowDate()); // 提交时间

        // 支付类型
        businessOrder.setPayType(platform);

        // 保存订单
        BusinessOrder orderResult = businessOrderService.insertBusinessOrder(businessOrder);

        // 根据生成的订单ID查询完整订单信息
        BusinessOrder createdOrder = selectBusinessOrderByOrderId(orderResult.getOrderId());
        if (createdOrder == null) {
            log.error("订单创建后查询失败，订单ID：{}", orderResult.getOrderId());
            throw new ServiceException("订单创建失败");
        }

        return createdOrder;
    }


    /**
     * 根据订单号查询订单
     *
     * @param orderCode
     * @return
     */
    @Override
    public BusinessOrder getByOrderCode(String orderCode) {
        // 修复：调用Mapper层方法根据订单号查询订单
        return businessOrderMapper.selectBusinessOrderByOrderCode(orderCode);
    }

    /**
     * 根据员工id获取交易订单列表
     */
    @Override
    public List<BusinessOrder> selectBusinessOrderByEmployeeId(Long employeeId) {
        return businessOrderMapper.selectBusinessOrderByEmployeeId(employeeId);
    }

    /**
     * 根据员工id和支付状态获取交易订单列表
     */
    @Override
    public List<BusinessOrder> selectBusinessOrderByEmployeeIdAndPayStatus(Long employeeId, String payStatus) {
        BusinessOrder orderQuery = new BusinessOrder();
        orderQuery.setEmployeeId(employeeId);

        // 当payStatus不为null时添加支付状态条件
        if (payStatus != null) {
            orderQuery.setPayStatus(payStatus);
        }

        return businessOrderMapper.selectBusinessOrderByEmployeeIdAndPayStatus(orderQuery);
    }

    /**
     * 根据员工id和订单状态获取交易订单列表
     */
    @Override
    public List<BusinessOrder> selectBusinessOrderByEmployeeIdAndOrderStatus(Long employeeId, String orderStatus) {
        BusinessOrder orderQuery = new BusinessOrder();
        orderQuery.setEmployeeId(employeeId);

        // 当orderStatus不为null时添加支付状态条件
        if (orderStatus != null) {
            orderQuery.setOrderStatus(orderStatus);
        }

        return businessOrderMapper.selectBusinessOrderByEmployeeIdAndOrderStatus(orderQuery);
    }


}